package com.bsoft.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import java.io.IOException;

//必须配置
@Configuration
public class FileUploadConfig {

    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxFileSize;

    @Value("${spring.servlet.multipart.max-request-size}")
    private String maxRequestSize;

    @Value("${spring.servlet.multipart.location:./temp-uploads}")
    private String uploadDir;

    /**
     * 手动注册MultipartResolver，解决自动配置失效问题
     */
    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver() throws IOException {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();

        // 动态解析配置值（需确保配置项存在）
        //单个文件最大值
        resolver.setMaxUploadSizePerFile(parseToBytes(maxFileSize));
        //单个文件最大值 整体文件最大值
        resolver.setMaxUploadSize(parseToBytes(maxRequestSize));
        resolver.setDefaultEncoding("UTF-8");
        resolver.setUploadTempDir(new FileSystemResource(uploadDir));
        // 延迟文件解析，避免在GET请求时解析multipart
        resolver.setResolveLazily(true);
        return resolver;
    }


    private long parseToBytes(String sizeStr) {
        sizeStr = sizeStr.toUpperCase();
        if (sizeStr.endsWith("MB")) {
            return Long.parseLong(sizeStr.replace("MB", "")) * 1024 * 1024;
        } else if (sizeStr.endsWith("KB")) {
            return Long.parseLong(sizeStr.replace("KB", "")) * 1024;
        } else {
            return Long.parseLong(sizeStr);
        }
    }

}
